const { nanoid } = require('nanoid'),
    Qiniu = require('qiniu'),
    crypto = require('crypto'),
    { cryptoSecret, qiniu } = require('../config/config');

function updateToQiniu(filePath, fileName) {
    Qiniu.conf.ACCESS_KEY = qiniu.keys.ak;
    Qiniu.conf.SECRET_KEY = qiniu.keys.sk;
    function uploadToken(bucket, key) {
        let policy = new Qiniu.rs.PutPolicy({
            isPrefixalScope: 1,
            scope: bucket + ':' + key
        })
        return policy.uploadToken();
    }
    const config = new Qiniu.conf.Config(),
        putExtra = new Qiniu.form_up.PutExtra(),
        formUploader = new Qiniu.form_up.FormUploader(config);
    const upToken = uploadToken(qiniu.bucket.blogsimg.bucket_name, fileName);

    return new Promise((resolve, reject) => {
        try {
            formUploader.putFile(upToken, fileName, filePath, putExtra, (err, data) => {
               
                if (err) {
                    console.log('qiniu upload error.(101)');
                    console.log(err);
                    reject('20001');
                    
                }
                console.log('qiniu upload successFully');
                let imgName = data.key;
                let url = qiniu.bucket.blogsimg.domain;
                let imgUrl = `${url}/${imgName}`;
                resolve(imgUrl)
            })
        } catch (error) {
            console.log('qiniu upload error.(102)');
            console.log(error);
            reject('20001');
        }
    })



}
function makeCrypto(str) {
    const _md5 = crypto.createHash('md5'),
        content = `str=${str}&secret=${cryptoSecret}`;
    return _md5.update(content).digest('hex')
}
function trimSpace(str) {
    return str.replace(/\s+/g, '');
}
function returnInfo(errorInfo, data) {
    if (data) {
        errorInfo.data = data
    }
    return errorInfo
}
// function 
module.exports = {
    updateToQiniu,
    makeCrypto,
    trimSpace,
    returnInfo
}     